import re
import pyperclip


class BracketCleaner:
    """按单元处理文本，清理指定括号内容"""

    def __init__(self, n: int = 2, m: int = 1, remove_content: bool = True):
        """
        n: 每个处理单元的行数
        m: 每个单元中需要处理的行号（从1开始）
        remove_content: True去除括号及其中内容，False只去除括号符号
        """
        self.n = n
        self.m = m
        self.remove_content = remove_content
        # 可自定义括号对
        self.brackets_list = [
            ('(', ')'),
            ('（', '）'),
            ('[', ']'),
            ('{', '}'),
            ('「', '」'),
        ]

    @staticmethod
    def remove_brackets(text: str, brackets: tuple, remove_content=True) -> str:
        """去除指定括号及其中内容，或只去除括号符号"""
        left, right = map(re.escape, brackets)
        if remove_content:
            pattern = f"{left}.*?{right}"
            return re.sub(pattern, '', text)
        else:
            pattern = f"{left}(.*?){right}"
            return re.sub(pattern, r'\1', text)

    def process_line(self, line: str) -> str:
        """处理单行文本，依次处理所有括号"""
        for brackets in self.brackets_list:
            line = self.remove_brackets(line, brackets, self.remove_content)
        return line

    def process_text(self, lines: list[str]) -> list[str]:
        """按单元处理文本"""
        processed_lines = []
        for i, line in enumerate(lines):
            unit_index = i // self.n
            line_in_unit = (i % self.n) + 1
            if line_in_unit == self.m:
                processed_lines.append(self.process_line(line))
            else:
                processed_lines.append(line)
        return processed_lines

    @staticmethod
    def read_input() -> list[str]:
        """从控制台读取多行文本，空行结束"""
        print("请输入多行文本（输入空行结束）：")
        lines = []
        while True:
            line = input()
            if line.strip() == "":
                break
            lines.append(line)
        return lines


if __name__ == "__main__":
    try:
        n = int(input("请输入每个处理单元的行数 n："))
    except ValueError:
        n = 2
        print("输入错误，使用默认 n=2")

    try:
        m = int(input(f"请输入每个单元中需要处理的行号 m（1~{n}）："))
    except ValueError:
        m = 1
        print("输入错误，使用默认 m=1")

    remove_content_input = input("是否去除括号内内容？输入 y 去除，n 只去除括号符号（默认 y）：").strip().lower()
    remove_content = (remove_content_input != 'n')

    lines = BracketCleaner.read_input()
    cleaner = BracketCleaner(n=n, m=m, remove_content=remove_content)
    processed_lines = cleaner.process_text(lines)

    result = '\n'.join(processed_lines)
    pyperclip.copy(result)
    print("\n处理完成，结果已复制到剪贴板：\n")
    print(result)
